<script setup lang="ts">
import { computed, ref } from 'vue'
import { ReGetOrderByOrderId, getMemberOrderByIdAPI, getMemberOrderPreAPI, getMemberOrderPreNowAPI, postMemberOrderAPI, updateOrder } from '@/services/order'
import type { OrderCreateParams, OrderResult, goods } from '@/types/order';
import { getGoodsByIdAPI } from '@/services/goods';
import { onLoad } from '@dcloudio/uni-app';
import { useAddressStore } from '@/stores/modules/address';
import { useMemberStore } from '@/stores';
import type { CartItem } from '@/types/cart';
import type { ProducTItem } from '@/types/global';
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
import { deleteSelected } from '@/services/cart'
import { watch } from 'vue';
// 订单备注
const buyerMessage = ref('')
// 单件商品的信息
const goodsData = ref<ProducTItem>()
//获取立即购买的商品属性
const getDealGoods = async (id: string) => {
  const res = await getGoodsByIdAPI(id)
  goodsData.value = res.data[0]
  orderPre.value = [{
    _id: "立即购买",
    id: goodsData.value._id,
    count: query.count ? Number(query.count) : 1,
    userID: memberStore.profile!.id,
    sku: goodsData.value.sku,
    name: goodsData.value.name,
    picture: goodsData.value.images[goodsData.value.cover],
    price: goodsData.value.price.original,
    nowPrice: goodsData.value.price.original,
    stock: goodsData.value.inventory.quantity,
    selected: false,
    isEffective: true

  }]
  console.log("立即购买的商品数据为:", goodsData.value)
}

//获取当前用户仓库
const memberStore = useMemberStore()
// 配送时间
const deliveryList = ref([
  { type: 1, text: '时间不限 (周一至周日)' },
  { type: 2, text: '工作日送 (周一至周五)' },
  { type: 3, text: '周末配送 (周六至周日)' },
])
// 当前配送时间下标
const activeIndex = ref(0)
// 当前配送时间
const activeDelivery = computed(() => deliveryList.value[activeIndex.value])
// 修改配送时间
const onChangeDelivery: UniHelper.SelectorPickerOnChange = (ev) => {
  activeIndex.value = ev.detail.value
}
// 获取页面参数
const query = defineProps<{
  skuId?: string,
  count?: string,
  addressId?: string,
  orderId?: string
}>()


//存储订单信息的变量
const orderPre = ref<CartItem[]>()
// 获取订单信息
const getMemberOrderPreData = async () => {
  if (query.count && query.skuId) {
    // const res = await getMemberOrderPreNowAPI({
    //   count: query.count,
    //   skuId: query.skuId,
    //   addressId: query.addressId
    // })
    // orderPre.value = res.result
  } else {
    const res = await getMemberOrderPreAPI(memberStore.profile!.id)
    orderPre.value = res.data
    for (let i = 0; i < orderPre.value.length; i++) {
      totalMoney.value = totalMoney.value + orderPre.value[i].nowPrice
      totalPostFee.value = 8 * orderPre.value!.length

      let item = {
        product_count: orderPre.value[i].count,
        product_cover: orderPre.value[i].picture,
        product_id: orderPre.value[i].id,
        product_name: orderPre.value[i].name,
        product_price: orderPre.value[i].nowPrice,
      }
      orderDetail.value?.productItems.push(item)
      console.log(orderPre.value)
    }
  }
}
//总金额
const totalMoney = ref(0)
//订单数据类型
const orderDetail = ref<OrderResult>()
//总运费
const totalPostFee = ref<number>(8)
//再次购买的信息
const reQueryGoods = async () => {
  if (query.orderId) {
    const res = await getMemberOrderByIdAPI(query.orderId)
    orderDetail.value = res.data[0]
    totalMoney.value = Number(orderDetail.value.total_amount)
    if (selectedAddress.value) {
      selectedAddress.value!.fullLocation = orderDetail.value.address.replace(' ' + orderDetail.value.address.split(' ')[3], '')
      selectedAddress.value!.address = orderDetail.value.address.split(' ')[3]
      selectedAddress.value!.receiver = orderDetail.value.receiver
    }
  }
}
// 提交订单
const onOrderSubmit = async () => {
  if (!selectedAddress.value?._id) {
    return uni.showToast({
      title: '请选择收货地址',
      icon: 'none',
    })
  } else if (query.orderId) {
    const res = await updateOrder(query.orderId, {
      address: address.value,
      message: buyerMessage.value ? buyerMessage.value : orderDetail.value?.message,
      order_state: "NEW",
      createTime: Date.now(),
      dieTime: Date.now() + 30 * 60 * 1000
    })
    if (res.code === 2000) {
      //关闭当前页面 跳转到订单详情页 传递订单id
      uni.redirectTo({ url: `/PagesOrder/detail/index?id=${orderDetail.value?.order_Id}` })
    } else {
      uni.showToast({
        title: "参数错误",
        icon: "error"
      })
    }
  }
  else {
    const res = await postMemberOrderAPI({
      user_Id: memberStore.profile!.id,
      order_state: 'NEW',
      total_amount: totalMoney.value.toString(),
      total_postFee: totalPostFee.value.toString(),
      pay_amount: (totalMoney.value + totalPostFee.value).toString(),
      receiver: selectedAddress.value.receiver,
      telephone: selectedAddress.value.telephone,
      address: selectedAddress.value.fullLocation + selectedAddress.value.address,
      productItems: orderPre.value!.map((v) => ({ product_count: v.count, product_name: v.name, product_id: v.id, product_cover: v.picture, product_price: v.nowPrice })),
      message: buyerMessage.value ? buyerMessage.value : '暂无备注',
    })
    orderPre.value![0]._id
    if (memberStore.profile) {
      await deleteSelected(memberStore.profile?.id)
    }

    //关闭当前页面 跳转到订单详情页 传递订单id
    uni.redirectTo({ url: `/PagesOrder/detail/index?id=${res.data}` })
  }
}
onLoad(() => {
  if (query.orderId) {
    reQueryGoods()
  } else if (query.skuId) {
    getDealGoods(query.skuId)
  } else {
    getMemberOrderPreData()
    console.log('获取商品成功')
  }
})

//实例化地址仓库
const addressStore = useAddressStore()
// 收货地址
const selectedAddress = computed(() => {
  return addressStore.selectedAddress || addressStore.defaultAddress
})
const address = computed(() => {
  if (selectedAddress.value) { return (selectedAddress.value?.fullLocation + ' ' + (selectedAddress.value?.address ? selectedAddress.value?.address : '')) }
})
</script>

<template>
  <scroll-view scroll-y class="viewport">
    <!-- 收货地址 -->
    <navigator v-if="orderDetail && !selectedAddress" class="shipment" hover-class="none"
      url="/pagesMember/address/index?from=order">
      <view class="user"> {{ orderDetail.receiver }}</view>
      <view class="address"> {{ orderDetail.address }} </view>
      <text class="icon icon-right"></text>
    </navigator>
    <navigator v-else-if="selectedAddress" class="shipment" hover-class="none"
      url="/pagesMember/address/index?from=order">
      <view class="user"> {{ selectedAddress.receiver }}</view>
      <view class="address"> {{ address }} </view>
      <text class="icon icon-right"></text>
    </navigator>
    <navigator v-else class="shipment" hover-class="none" url="/pagesMember/address/index?from=order">
      <view class="address"> 请选择收货地址 </view>
      <text class="icon icon-right"></text>
    </navigator>
    <!-- 商品信息 -->
    <view class="goods" v-if="orderPre">
      <navigator v-for="item in orderPre" :key="item.id" :url="`/pages/goods/index?id=${item.id}`" class="item"
        hover-class="none">
        <image class="picture" :src="item.picture" />
        <view class="meta">
          <view class="name ellipsis">{{ item.name }}</view>
          <!-- <view class="attrs">{{ item.attrsText }}</view>-->
          <view class="prices">
            <view class="pay-price symbol">{{ item.nowPrice }}</view>
            <view class="price symbol">{{ item.price }}</view>
          </view>
          <view class="count">x{{ item.count }}</view>
        </view>
      </navigator>
    </view>
    <!-- 商品信息 -->
    <view class="goods" v-if="orderDetail?.productItems">
      <navigator v-for="item in orderDetail?.productItems" :key="item.product_id"
        :url="`/pages/goods/index?id=${item.product_id}`" class="item" hover-class="none">
        <image class="picture" :src="item.product_cover" />
        <view class="meta">
          <view class="name ellipsis">{{ item.product_name }}</view>
          <view class="prices">
            <view class="pay-price symbol">{{ item.product_price }}</view>
            <view class="price symbol">{{ item.product_price }}</view>
          </view>
          <view class="count">x{{ item.product_count }}</view>
        </view>
      </navigator>
    </view>

    <!-- 配送及支付方式 -->
    <view class="related">
      <!-- <view class="item">
        <text class="text">配送时间</text>
        <picker :range="deliveryList" range-key="text" @change="onChangeDelivery">
          <view class="icon-fonts picker">{{ activeDelivery.text }}</view>
        </picker>
      </view> -->
      <view class="item">
        <text class="text">订单备注</text>
        <input class="input" :cursor-spacing="30" placeholder="选题，建议留言前先与商家沟通确认" v-model="buyerMessage" />
      </view>
    </view>

    <!-- 支付金额 -->
    <view class="settlement">
      <view class="item">
        <text class="text">商品总价: </text>
        <text class="number symbol">{{ totalMoney.toFixed(2) }}</text>
      </view>
      <view class="item">
        <text class="text">运费: </text>
        <text class="number symbol">{{ totalPostFee.toFixed(2) }}</text>
      </view>
    </view>
    <view style="height:100rpx">
    </view>
  </scroll-view>

  <!-- 吸底工具栏 -->
  <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="total-pay symbol">
      <text class="number">{{ (totalMoney + totalPostFee).toFixed(2) }}</text>
    </view>
    <view class="button" :class="{ disabled: !selectedAddress?._id }" @tap="onOrderSubmit"> 提交订单 </view>
  </view>
</template>
!
<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background-color: #f4f4f4;
}

.symbol::before {
  content: '¥';
  font-size: 80%;
  margin-right: 5rpx;
}

.shipment {
  margin: 20rpx;
  padding: 30rpx 30rpx 30rpx 84rpx;
  font-size: 26rpx;
  border-radius: 10rpx;
  background: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/locate.png) 20rpx center / 50rpx no-repeat #fff;
  position: relative;

  .icon {
    font-size: 36rpx;
    color: #333;
    transform: translateY(-50%);
    position: absolute;
    top: 50%;
    right: 20rpx;
  }

  .user {
    color: #333;
    margin-bottom: 5rpx;
  }

  .address {
    color: #666;
  }
}

.goods {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    padding: 30rpx 0;
    border-top: 1rpx solid #eee;

    &:first-child {
      border-top: none;
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrs {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .prices {
      display: flex;
      align-items: baseline;
      margin-top: 6rpx;
      font-size: 28rpx;

      .pay-price {
        margin-right: 10rpx;
        color: #cf4444;
      }

      .price {
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }
    }

    .count {
      position: absolute;
      bottom: 0;
      right: 0;
      font-size: 26rpx;
      color: #444;
    }
  }
}

.related {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .input {
    flex: 1;
    text-align: right;
    margin: 20rpx 0;
    padding-right: 20rpx;
    font-size: 26rpx;
    color: #999;
  }

  .item .text {
    width: 125rpx;
  }

  .picker {
    color: #666;
  }

  .picker::after {
    content: '\e6c2';
  }
}

/* 结算清单 */
.settlement {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .danger {
    color: #cf4444;
  }
}

/* 吸底工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;

  .total-pay {
    font-size: 40rpx;
    color: #cf4444;

    .decimal {
      font-size: 75%;
    }
  }

  .button {
    width: 220rpx;
    text-align: center;
    line-height: 72rpx;
    font-size: 26rpx;
    color: #fff;
    border-radius: 72rpx;
    background-color: #27ba9b;
  }

  .disabled {
    opacity: 0.6;
  }
}
</style>
